﻿using GalaSoft.MvvmLight.Messaging;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using WPRD.Extensions;
using WPRD.Models;

namespace WPRD.Views
{
    /// <summary>
    /// RadarSiteConfig.xaml 的交互逻辑
    /// </summary>
    public partial class RadarSiteConfigView : Window
    {
        public RadarSiteConfigView()
        {
            InitializeComponent();

            //注册MVVMLight消息
            Messenger.Default.Register<object>(this, "OpenAddRadarSiteView", OpenAddRadarSiteView);
            Messenger.Default.Register<RadarSite>(this, "OpenEditRadarSiteView", OpenEditRadarSiteView);
            Messenger.Default.Register<object>(this, "CloseRadarSiteConfigView", CloseView);
            Messenger.Default.Register<DataGridTextColumn>(this, "SortRadarSites", SortRadarSiteDataGrid);

            //当前元素移除时卸载MVVMLight消息
            this.Unloaded += (sender, e) => Messenger.Default.Unregister(this);
            //默认选中第一个台站
            this.Dispatcher.InvokeAsync(() => this.radarSiteDataGrid.SelectedIndex = 0, DispatcherPriority.Loaded, CancellationToken.None);
        }


        #region Message Handler
        /// <summary>
        /// 打开添加台站视图
        /// </summary>
        /// <param name="obj"></param>
        private void OpenAddRadarSiteView(object obj)
        {
            AddRadarSiteView addRadarSiteView = new AddRadarSiteView();
            //设置台站
            Messenger.Default.Send<RadarSite>(new RadarSite(), "SetRadarSite");
            addRadarSiteView.Owner = this;
            addRadarSiteView.ShowDialog();
        }

        /// <summary>
        /// 打开编辑台站视图
        /// </summary>
        /// <param name="radarSite"></param>
        private void OpenEditRadarSiteView(RadarSite radarSite)
        {
            EditRadarSiteView editRadarSiteView = new EditRadarSiteView();
            //设置台站
            Messenger.Default.Send<RadarSite>(radarSite, "SetRadarSite");
            editRadarSiteView.Owner = this;
            editRadarSiteView.ShowDialog();
        }

        /// <summary>
        /// 台站排序
        /// </summary>
        /// <param name="columnName">排序列名</param>
        private void SortRadarSiteDataGrid(DataGridTextColumn column)
        {
            //模拟表格排序
            if (radarSiteDataGrid.ItemsSource != null)
                radarSiteDataGrid.SimulateSort(column.SortMemberPath, column.SortDirection);
        }

        /// <summary>
        /// 关闭视图
        /// </summary>
        private void CloseView(object obj)
        {
            this.Close();
        }
        #endregion
    }
}
